package com.webtest.checkcodetest;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/8 16:25
 */
public class ImageServlet extends HttpServlet {
    private static final long serialVersionUID = -5676708737260568225L;
    private static final int NUMBER_OF_CHS = 4;
    private static final int IMG_WIDTH = 65;
    private static final int IMG_HEIGHT = 25;
    private static Random r = new Random();
    private static char[] chs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 实例化BufferedImage
        BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // 验证码图片的背景颜色
        Color c = new Color(200, 200, 255);
        g.setColor(c);
        // 图片的边框
        g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
        // 用于保存验证码字符串
        StringBuffer sb = new StringBuffer();
        // 数组的下标
        int index;
        for (int i = 0; i < NUMBER_OF_CHS; i++) {
            // 随机一个下标
            index = r.nextInt(chs.length);
            // 随机一个颜色
            g.setColor(new Color(r.nextInt(88), r.nextInt(210), r.nextInt(150)));
            // 画出字符
            g.drawString(chs[index] + "", 15 * i + 3, 18);
            // 验证码字符串
            sb.append(chs[index]);
        }
        // 将验证码字符串保存到session中
        req.getSession().setAttribute("piccode", sb.toString());
        // 向页面输出图像
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }
}
